"use client";
import { Button } from "@/components/ui/button";
import {
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form";
import { Check, ChevronsDownUp, ChevronsUpDown } from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { regions } from "@/lib/region";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Virtuoso } from 'react-virtuoso'
import { useFormContext } from "react-hook-form";


interface SelectProps {
    label?: string;
    name: string;
    options: { value: string; label: string }[];
    placeholder?: string;
}

export const Select = ({ placeholder, label, name, options }: SelectProps) => {
    const { control, setValue, getValues } = useFormContext();
    const [searchQuery, setSearchQuery] = useState("");
    const [isOpen, setIsOpen] = useState(false);
    const filteredOptions = useMemo(() => {
        if (!searchQuery) return options;
        return options.filter(option =>
            option.label.toLowerCase().includes(searchQuery.toLowerCase())
        );
    }, [options, searchQuery]);
    // 处理选择事件
    const handleSelect = useCallback((regionValue: string) => {
        const currentValue = getValues(name);
        const newValue = regionValue === currentValue ? "" : regionValue;
        setValue(name, newValue, { shouldValidate: true });
        setIsOpen(false);
        setSearchQuery(""); // 选择后清空搜索查询
    }, [getValues, name, setValue]);
    // Virtuoso 项渲染器
    const itemRenderer = useCallback((index: number) => {
        const option = filteredOptions[index];
        const currentValue = getValues(name);
        const isSelected = currentValue === option.value;

        return (
            <CommandItem
                key={option.value}
                value={option.label}
                onSelect={() => handleSelect(option.value)}
                className={cn(
                    "flex items-center justify-between",
                    isSelected && "bg-accent"
                )}
            >
                {option.label}
                <Check
                    className={cn(
                        "ml-auto h-4 w-4",
                        isSelected ? "opacity-100" : "opacity-0"
                    )}
                />
            </CommandItem>
        );
    }, [filteredOptions, getValues, handleSelect, name]);
    return (
        <FormField
            control={control}
            name={name}
            render={({ field }) => {
                const selectedRegion = regions.find(region => region.value === field.value);
                return (
                    <FormItem className="flex flex-col">
                        {label ? <FormLabel>{label}</FormLabel> : null}
                        <Popover open={isOpen} onOpenChange={setIsOpen}>
                            <PopoverTrigger asChild>
                                <FormControl>
                                    <Button
                                        variant="outline"
                                        role="combobox"
                                        className={cn(
                                            "w-full justify-between bg-transparent",
                                            !field.value && "text-muted-foreground"
                                        )}
                                    >
                                        {field.value
                                            ? selectedRegion?.label
                                            : (placeholder ? placeholder : "Select option...")}
                                        {isOpen ? <ChevronsDownUp className="opacity-50" /> : <ChevronsUpDown className="opacity-50" />}
                                    </Button>
                                </FormControl>
                            </PopoverTrigger>
                            <PopoverContent className="p-0" align="start" style={{
                                width: "var(--radix-popover-trigger-width)",
                                maxWidth: "100%"
                            }}>
                                <Command shouldFilter={false}>
                                    <CommandInput
                                        placeholder="Search option..."
                                        className="h-9"
                                        value={searchQuery}
                                        onValueChange={setSearchQuery}
                                    />
                                    <CommandList>
                                        <CommandEmpty>No region found.</CommandEmpty>
                                        <CommandGroup>
                                            <Virtuoso
                                                style={{ height: Math.min(filteredOptions.length * 36, 240) }}
                                                initialTopMostItemIndex={!getValues(name) ? 0 : filteredOptions.findIndex(option => option.value === getValues(name))}
                                                totalCount={filteredOptions.length}
                                                itemContent={itemRenderer}
                                                overscan={10}
                                            />
                                        </CommandGroup>
                                    </CommandList>
                                </Command>
                            </PopoverContent>
                        </Popover>
                        <FormMessage />
                    </FormItem>
                );
            }}
        />
    );
};
